from django.http import Http404, HttpResponse
from google.appengine.api import urlfetch

import oauth

from twitter_login import credentials, models


class AuthenticatedTwitterFeed(object):

    method = urlfetch.GET

    def __init__(self, type_, url):
        self.type_ = type_
        self._url = url

    def __call__(self, request, key):
        """Call 'url' on behalf of 'key'."""
        user = models.TwitterUser.get_by_key_name(key)
        if user is None:
            raise Http404
        client = oauth.TwitterClient(*credentials.oauth_args)
        result = client.make_request(self._url, user.token, user.secret,
                                        method=self.method)
        if result.status_code != 200:
            # XXX how to handle errors?
            pass
        response = HttpResponse(result.content,
                                mimetype='application/atom+xml')
        # XXX Copy over some headers?
        return response


mentions = AuthenticatedTwitterFeed('Mentions',
        'http://api.twitter.com/1/statuses/mentions.atom')
direct_messages = AuthenticatedTwitterFeed('Direct Messages',
        'http://api.twitter.com/1/direct_messages.atom')
timeline = AuthenticatedTwitterFeed('Timeline',
        'http://api.twitter.com/1/statuses/home_timeline.atom')
